package org.example.servicelogin.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Map;

@Component
public class JwtUtil {

    public static String SECRET;
    public static long EXPIRE_TIME;

    /**
     * 生成JWT令牌
     */
    public static String generateToken(Map<String, Object> map) {
        Date now = new Date();
        Date expireDate = new Date(now.getTime() + EXPIRE_TIME);

        return JWT.create()
                .withClaim("claim", map)
                .withIssuedAt(now)
                .withExpiresAt(expireDate)
                .sign(Algorithm.HMAC256(SECRET.getBytes(StandardCharsets.UTF_8)));
    }

    /**
     * 验证JWT令牌
     */
    private static DecodedJWT verifyToken(String token) {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET.getBytes(StandardCharsets.UTF_8))).build();
        return verifier.verify(token);
    }

    /**
     * 从令牌中获取ID
     */
    public static Map<String, Object> getIdFromToken(String token) {
        DecodedJWT jwt = verifyToken(token);

        return jwt.getClaim("claim").asMap();
    }
}
